package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.base.IBaseEnum;
import com.settlement.system.common.enums.BillCheckStatusEnum;
import com.settlement.system.common.result.Result;
import com.settlement.system.listener.easyexcel.BillProjectConfigConfigListener;
import com.settlement.system.listener.easyexcel.TmBillConfigConditionListener;
import com.settlement.system.model.entity.SysColumnMatch;
import com.settlement.system.model.entity.SysColumnMatchCondition;
import com.settlement.system.model.form.ColumnMatchForm;
import com.settlement.system.model.vo.BillProjectConfigImportVo;
import com.settlement.system.model.vo.TmBillConfigConditionImportVo;
import com.settlement.system.model.vo.TmBillConfigImportVo;
import com.settlement.system.service.SysColumnMatchService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 字段对应关系 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2023-09-19
 */
@RestController
@RequestMapping("/api/v1/billColumnMatch")
@RequiredArgsConstructor
public class SysBillColumnMatchController {
    private final SysColumnMatchService sysColumnMatchService;

    @Operation(summary = "保存字段对应关系", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:columnMatch:save')")
    public Result<?> saveColumnMatch(@Valid @RequestBody ColumnMatchForm columnMatchForm) {
        return Result.success(sysColumnMatchService.saveForm(columnMatchForm));
    }

    @Operation(summary = "删除字段对应关系", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:columnMatch:delete')")
    public Result<?> deleteMatch(@Parameter(description = "字段对应关系ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysColumnMatchService.deleteMatch(ids);
        return Result.judge(result);
    }

    @Operation(summary = "字段对应关系数据", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{platformKey}/form")
    public Result<?> getColumnMatchForm(@Parameter(description = "平台KEY") @PathVariable String platformKey) {
        return Result.success(sysColumnMatchService.getByPlatform(platformKey));
    }

    @Operation(summary = "平台账单项目配置导出", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/billConfigExport/{platformKey}")
    @PreAuthorize("@ss.hasPerm('sys:billColumnMatch:billConfigExport')")
    @PreventDuplicateSubmit
    public void billConfigExport(HttpServletResponse response, @PathVariable String platformKey) throws Exception {
        List<BillProjectConfigImportVo> importVoList = new ArrayList<>();
        List<TmBillConfigConditionImportVo> conditionImportVoList = new ArrayList<>();
        List<SysColumnMatch> sysColumnMatches = sysColumnMatchService.getByPlatform(platformKey);
        BillProjectConfigImportVo importVo;
        TmBillConfigConditionImportVo conditionImportVo;
        int index = 1;
        for (SysColumnMatch sysColumnMatch : sysColumnMatches) {
            importVo = new BillProjectConfigImportVo();
            BeanUtils.copyProperties(sysColumnMatch, importVo);
            importVo.setBillCheckName(IBaseEnum.getLabelByValue(sysColumnMatch.getBillCheck(), BillCheckStatusEnum.class));
            importVo.setConfigId("配置%s".formatted(index));
            importVoList.add(importVo);
            index ++;
            // 处理条件
            if(sysColumnMatch.getConditionList() != null && sysColumnMatch.getConditionList().size() > 0){
                for (SysColumnMatchCondition condition : sysColumnMatch.getConditionList()) {
                    conditionImportVo = new TmBillConfigConditionImportVo();
                    BeanUtils.copyProperties(condition, conditionImportVo);
                    conditionImportVo.setConfigId(importVo.getConfigId());
                    conditionImportVoList.add(conditionImportVo);
                }
            }
        }
        String fileName = "平台账单项目配置.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        //将数据写入sheet页中
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet1 = EasyExcel.writerSheet(0, "平台账单项目配置").head(BillProjectConfigImportVo.class).build();
        WriteSheet writeSheet2 = EasyExcel.writerSheet(1, "符合条件").head(TmBillConfigConditionImportVo.class).build();
        excelWriter.write(importVoList, writeSheet1);
        excelWriter.write(conditionImportVoList, writeSheet2);
        excelWriter.finish();
        response.flushBuffer();
    }

    @Operation(summary = "平台账单项目配置导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/billConfigImport/{platformKey}")
    @PreAuthorize("@ss.hasPerm('sys:billColumnMatch:billConfigImport')")
    @PreventDuplicateSubmit
    public Result<?> billConfigImport(@RequestParam("file") MultipartFile file, @Parameter(description = "平台KEY") @PathVariable String platformKey) throws Exception {
        BillProjectConfigConfigListener listener = new BillProjectConfigConfigListener();
        TmBillConfigConditionListener configConditionListener = new TmBillConfigConditionListener();
        EasyExcelFactory.read(file.getInputStream(), BillProjectConfigImportVo.class, listener).sheet(0).doRead();
        EasyExcelFactory.read(file.getInputStream(), TmBillConfigConditionImportVo.class, configConditionListener).sheet(1).doRead();
        sysColumnMatchService.saveConfig(listener.getVos(), configConditionListener.getVos(), platformKey);
        return Result.success();
    }
}
